<template>
  <div class="app-container">
    <el-page-header
      @back="goBack"
      style="padding-top: 25px; padding-bottom: 10px; padding-left: 15px"
    >
      <template #content>
        <span class="text-large font-600 mr-3"> {{ title }} </span>
      </template>
    </el-page-header>
    <el-form
      ref="userFormRef"
      :model="formData"
      :rules="rules"
      label-width="80px"
    >
      <el-row :gutter="20">
        <el-col :span="18">
          <el-card class="box-card">
            <el-form-item label="名称" prop="title">
              <editor
                v-model="formData.title"
                style="height: calc(30vh - 120px); z-index: 99"
              /> </el-form-item
            ><br /><br /><br />
            <el-form-item label="解析" prop="explain_content">
              <el-input
                v-model="formData.explain_content"
                type="textarea"
                placeholder="请输入解析"
              />
            </el-form-item>

            <el-form-item v-if="isShowForm" label="选项">
              <el-button type="primary" plain @click="addOptions"
                ><el-icon><Plus /></el-icon>&nbsp;添加选项</el-button
              >
              <el-table :data="pageData" style="width: 100%; padding-top: 15px">
                <el-table-column prop="index" label="序号" width="80">
                  <template #default="scope"> {{ scope.$index + 1 }} </template>
                </el-table-column>
                <el-table-column label="是否是答案" width="180">
                  <template #default="scope">
                    <el-checkbox v-model="scope.row.is_right">
                      答案
                    </el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column label="选项">
                  <template #default="scope">
                    <el-input type="textarea" v-model="scope.row.title" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template #default="scope">
                    <el-button
                      type="danger"
                      icon="Delete"
                      circle
                      @click="deleteOptions(scope.$index)"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item v-if="isShowFormChoose" label="选项">
              <el-radio-group
                v-model="formData.is_right"
                @change="chooseChange"
              >
                <el-radio :value="1">正确</el-radio>
                <el-radio :value="0">错误</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-card>
        </el-col>
        <el-col :span="5">
          <el-card class="box-card">
            <el-form-item label="学科" prop="subject_id">
              <el-select v-model="formData.subject_id" placeholder="请选择学科">
                <el-option
                  v-for="item in subjectOptions"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="题型" prop="type">
              <el-select
                v-model="formData.type"
                @change="categoryType"
                placeholder="请选择题型"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="难度" prop="difficulty_rate">
              <el-rate v-model="formData.difficulty_rate" />
            </el-form-item>
            <el-form-item v-if="formData.type > 2" label="答案" prop="answer">
              <el-input
                v-model="formData.answer"
                type="textarea"
                placeholder="请输入答案"
              />
            </el-form-item>
            <el-form-item label="分数" prop="score">
              <el-input-number
                v-model="formData.score"
                :precision="1"
                :step="0.1"
                controls-position="right"
                :min="0"
                style="width: 100px"
              />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input-number
                v-model="formData.sort"
                controls-position="right"
                :min="0"
                style="width: 100px"
              />
            </el-form-item>

            <el-form-item label="状态" prop="is_hid">
              <el-radio-group v-model="formData.is_hid">
                <el-radio :value="0">正常</el-radio>
                <el-radio :value="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSubmit">保 存</el-button>
              <el-button @click="goBack">取 消</el-button>
            </el-form-item>
          </el-card>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { useRoute } from "vue-router";

defineOptions({
  name: "TopicAdd",
  inheritAttrs: false,
});
import Editor from "@/components/WangEditor/index.vue";
import { addTopic, updateTopic, getTopicForm, getOptions } from "@/api/topic";
import { getSubjectAll } from "@/api/subject";
import { SubjectForm } from "@/api/subject/types";
import { TopicForm, TopicOptions, TopicSelectOptions } from "@/api/topic/types";
const options = ref<TopicOptions[]>(); // 下拉数据源
const subjectOptions = ref<SubjectForm[]>();
const pageData = ref<TopicSelectOptions[]>(); // 分页数据
const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 表单
const isShowForm = ref(false);
const isShowFormChoose = ref(false);
const title = ref("");
const loading = ref(false); //  加载状态
// 表单数据
const formData = reactive<TopicForm>({
  is_hid: 0,
  score: 1,
  sort: 0,
});
// 校验规则
const rules = reactive({
  title: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  type: [{ required: true, message: "题型不能为空", trigger: "blur" }],
  score: [{ required: true, message: "分数不能为空", trigger: "blur" }],
  difficulty_rate: [
    { required: true, message: "难度不能为空", trigger: "blur" },
  ],
  explain_content: [
    { required: true, message: "解析不能为空", trigger: "blur" },
  ],
  subject_id: [{ required: true, message: "学科不能为空", trigger: "blur" }],
});

function loadOptions() {
  getOptions().then((response) => {
    options.value = response.data;
  });
}

function addOptions() {
  const options = {
    title: "",
    is_right: 0,
  };
  pageData.value?.push(options);
}

function deleteOptions(index: number) {
  pageData.value?.splice(index, 1);
}

function goBack() {
  window.history.back();
}
function getTopic() {
  const route = useRoute();
  getTopicForm(route.query.id).then(({ data }) => {
    Object.assign(formData, { ...data });
    categoryType(formData.type);
    pageData.value = formData.options;
    pageData.value.forEach((item) => {
      item.is_right = item.is_right == 1;
    });
  });
}
/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    loading.value = true;
    if (valid) {
      const ids = formData.id;
      formData.options = pageData.value;
      if (ids) {
        updateTopic(formData)
          .then(() => {
            ElMessage.success("修改成功");
          })
          .finally(() => (loading.value = false));
      } else {
        addTopic(formData)
          .then(() => {
            ElMessage.success("新增成功");
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);

function categoryType(value: any) {
  if (value == 3) {
    isShowFormChoose.value = true;
    isShowForm.value = false;
  } else {
    isShowForm.value = value < 4;
  }
  if (value > 2) {
    rules.answer = [
      { required: true, message: "答案不能为空", trigger: "blur" },
    ];
  }
}

function chooseChange(value: any) {
  if (value == 1) {
    formData.answer = "正确";
  } else {
    formData.answer = "错误";
  }
}

onMounted(() => {
  loadOptions();
  getSubjectAll().then(({ data }) => {
    subjectOptions.value = data;
  });
  const route = useRoute();
  if (route.query.id) {
    title.value = "编辑题目";
    getTopic();
  } else {
    pageData.value = [
      {
        title: "",
        is_right: 0,
      },
    ];
    title.value = "创建题目";
  }
});
</script>
<style></style>
